package com.tyut.musicdreamer.service.music.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tyut.musicdreamer.service.music.model.dto.MusicCreateRequest;
import com.tyut.musicdreamer.service.music.model.dto.MusicQueryRequest;
import com.tyut.musicdreamer.service.music.model.dto.PresignedUrlRequest;
import com.tyut.musicdreamer.service.music.model.dto.PresignedUrlResponse;
import com.tyut.musicdreamer.service.music.model.vo.MusicVO;
import com.tyut.musicdreamer.service.music.service.MusicService;
import com.tyut.musicdreamer.service.music.service.MusicStorageService;
import com.tyut.musicdreamer.service.music.service.impl.StorageServiceAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 音乐管理员控制器
 */
@RestController
@RequestMapping("/api/music/admin")
@RequiredArgsConstructor
@Slf4j
public class MusicAdminController {

    private static final String USER_ID_HEADER = "X-User-ID";
    private static final String USER_ROLE_HEADER = "X-User-Role";
    
    private final MusicService musicService;
    private final MusicStorageService musicStorageService;

    /**
     * 生成预签名上传URL
     * 用于管理员直接上传大文件到OSS
     */
    @PostMapping("/presigned-url")
    public PresignedUrlResponse generatePresignedUrl(
            @RequestBody PresignedUrlRequest request,
            @RequestHeader(USER_ID_HEADER) Long userId,
            @RequestHeader(USER_ROLE_HEADER) String userRole) {
        
        // 验证角色权限
        if (!"ADMIN".equals(userRole)) {
            throw new IllegalArgumentException("权限不足，需要管理员权限");
        }
        
        log.debug("生成预签名上传URL, 用户ID: {}, 文件名: {}", userId, request.getFilename());
        
        // 只有在使用OSS存储时才支持预签名URL
        if (!(musicStorageService instanceof StorageServiceAdapter storageAdapter)) {
            throw new UnsupportedOperationException("当前存储服务不支持预签名URL上传");
        }
        
        // 生成预签名URL
        String url = storageAdapter.generatePresignedUrl(
                request.getFilename(),
                request.getExpirationMinutes() > 0 ? request.getExpirationMinutes() : 30
        );
        
        // 返回响应
        PresignedUrlResponse response = new PresignedUrlResponse();
        response.setUrl(url);
        response.setExpiration(System.currentTimeMillis() + (request.getExpirationMinutes() * 60 * 1000L));
        
        // 提取对象键，用于后续创建音乐记录
        String objectKey = url.substring(url.lastIndexOf("/") + 1);
        if (objectKey.contains("?")) {
            objectKey = objectKey.substring(0, objectKey.indexOf("?"));
        }
        response.setObjectKey(objectKey);
        
        return response;
    }
    
    /**
     * 完成上传并创建音乐记录
     * 当文件上传到OSS后，前端调用此接口创建音乐记录
     */
    @PostMapping("/complete-upload")
    public MusicVO completeUpload(
            @RequestBody MusicCreateRequest request,
            @RequestHeader(USER_ID_HEADER) Long userId,
            @RequestHeader(USER_ROLE_HEADER) String userRole) {
        
        // 验证角色权限
        if (!"ADMIN".equals(userRole)) {
            throw new IllegalArgumentException("权限不足，需要管理员权限");
        }
        
        log.debug("完成上传并创建音乐记录, 用户ID: {}, 标题: {}", userId, request.getTitle());
        
        // 设置用户ID
        request.setUserId(userId);
        
        // 创建音乐记录
        return musicService.createMusic(request);
    }
    
    /**
     * 更新音乐存储类别
     * 根据播放次数自动调整存储类别
     */
    @PostMapping("/update-storage-class")
    public Map<String, Object> updateStorageClass(
            @RequestHeader(USER_ID_HEADER) Long userId,
            @RequestHeader(USER_ROLE_HEADER) String userRole) {
        
        // 验证角色权限
        if (!"ADMIN".equals(userRole)) {
            throw new IllegalArgumentException("权限不足，需要管理员权限");
        }
        
        log.debug("更新音乐存储类别, 用户ID: {}", userId);
        
        // 只有在使用OSS存储时才支持更新存储类别
        if (!(musicStorageService instanceof StorageServiceAdapter)) {
            throw new UnsupportedOperationException("当前存储服务不支持更新存储类别");
        }
        
        // TODO: 实现根据播放次数更新存储类别的逻辑
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "存储类别更新任务已启动");
        return result;
    }
    
    /**
     * 管理员查询所有音乐
     */
    @GetMapping("/music/list")
    public Page<MusicVO> listAllMusic(
            MusicQueryRequest request,
            @RequestHeader(USER_ID_HEADER) Long userId,
            @RequestHeader(USER_ROLE_HEADER) String userRole) {
        
        // 验证角色权限
        if (!"ADMIN".equals(userRole)) {
            throw new IllegalArgumentException("权限不足，需要管理员权限");
        }
        
        log.debug("管理员查询所有音乐, 用户ID: {}", userId);
        return musicService.pageMusicList(request);
    }
} 